package com.deer.wms.instock.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.ASN.manage.dao.AsnDetailMapper;
import com.deer.wms.ASN.manage.dao.AsnMasterMapper;
import com.deer.wms.ASN.manage.model.asn.AsnDetail;
import com.deer.wms.ASN.manage.model.asn.AsnMaster;
import com.deer.wms.ASN.manage.model.in.AcceptRecord;
import com.deer.wms.ASN.manage.service.AcceptRecordService;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.base.system.dao.ErpBackRecordMapper;
import com.deer.wms.base.system.model.*;
import com.deer.wms.base.system.model.Cell.CellInfo;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.service.CellInfoService;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.instock.constant.InStockConstant;
import com.deer.wms.instock.dao.TransferBillMapper;
import com.deer.wms.instock.model.Allot.TransferBillCriteria;
import com.deer.wms.instock.model.disptch.DispatCriteria;
import com.deer.wms.instock.model.transfer.TransferBill;
import com.deer.wms.instock.model.transfer.Upper;
import com.deer.wms.instock.model.transfer.UpperData;
import com.deer.wms.instock.service.TransferBillService;
import com.deer.wms.instock.service.enter.StrategyEnterService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.InventoryTransact;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.inventory.service.ItemBatchService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.deer.wms.system.manage.service.CodeRuleService;
import com.deer.wms.system.manage.service.WareInfoService;
import com.deer.wms.ware.task.model.pushErp.StrategyErpService;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.model.ErpPushLog;
import com.deer.wms.ware.task.model.ErpPushLogInfo;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.model.SO.SoMaster;
import com.deer.wms.ware.task.model.SO.vo.SoDetailVo;
import com.deer.wms.ware.task.model.Wave.WaveDetail;
import com.deer.wms.ware.task.model.Wave.WaveMaster;
import com.deer.wms.ware.task.model.out.OutDetail;
import com.deer.wms.ware.task.model.pushErp.beasAssist.BaseAssist;
import com.deer.wms.ware.task.service.*;
import com.deer.wms.ware.task.service.impl.SoMasterServiceImpl;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.deer.wms.project.root.util.CollectionUtils.convertMap;

/**
 * @author : wei
 * @since : 2022-01-08 20:43:41
 **/
@Service
@Transactional
public class TransferBillServiceImpl extends SuperServiceImpl<TransferBillMapper, TransferBill> implements TransferBillService {

    @Autowired
    private CodeRuleService codeRuleService;
    @Autowired
    private InventoryTransactService inventoryTransactService;
    @Autowired
    private WareInfoService wareInfoService;
    @Autowired
    private CellInfoService cellInfoService;
    @Autowired
    private ItemInfoService itemInfoService;
    @Autowired
    private ItemBatchService itemBatchService;
    @Autowired
    private TransferBillMapper transferBillMapper;
    @Autowired
    private AsnMasterMapper asnMasterMapper;
    @Autowired
    private AsnDetailMapper asnDetailMapper;
    @Autowired
    private ErpBackRecordMapper erpBackRecordMapper;
    @Autowired
    private SoMasterServiceImpl soMasterService;
    @Autowired
    private PushErpService pushErpService;
    @Autowired
    private SoDetailService soDetailService;
    @Autowired
    private AsnMasterService asnMasterService;
    @Autowired
    private WaveDetailService waveDetailService;
    @Autowired
    private WaveMasterService waveMasterService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private ErpPushLogService erpPushLogService;

    @Autowired
    private OutDetailService outDetailService;
    @Autowired
    private OutMasterService outMasterService;

    @Autowired
    private ErpPushLogInfoService erpPushLogInfoService;

    @Autowired
    private PickTaskService pickTaskService;
    @Autowired
    private StrategyErpService strategyErpService;

    @Autowired
    private AsyncService asyncService;
    @Autowired
    private AcceptRecordService acceptRecordService;
    @Autowired
    private StrategyEnterService strategyEnterService;


    @Override
    public List<TransferBill> saveAndConfirmTransferBill(List<TransferBill> transferBills) {
        List<TransferBill> list = this.createTransferBill(transferBills);
        return this.confirmTransferBill(list);
    }

    @Override
    public List<TransferBill> createTransferBill(List<TransferBill> transferBills) {
        for (TransferBill transferBill : transferBills) {
            //Step1.各类数据数据校验，不合法给与异常信息提示
            //仓库 来源库位  目标库位  来源容器  目标容器  物料  批次
            this.validateAndPrepareTransferData(transferBill);

            //Step2.单据号  codeRuleService.generateCode(SystemManageConstant.CODE_RULE_TRANS)
            transferBill.setTransferBillCode(codeRuleService.generateCodeByRedis(SystemManageConstant.CODE_RULE_TRANS));
            //状态
            transferBill.setState(InStockConstant.TRANS_STATE_INIT);
        }
        //Step3.统一保存
        this.saveBatch(transferBills);

        return transferBills;
    }


    @Override
    public List<TransferBill> confirmTransferBill(List<TransferBill> transferBills) {
        for (TransferBill transferBill : transferBills) {
            //Step1.判断转移单是否满足确认的条件 修改状态
            if (ObjectUtil.notEqual(InStockConstant.TRANS_STATE_INIT, transferBill.getState())) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "转移单不为新建状态，不可确认!");
            }
            transferBill.setState(InStockConstant.TRANS_STATE_FINISHED);
            transferBill.setConfirmTime(DateUtil.now());

            //Step2.生成库存事务请求 并提交(事务提交，修改库存)
            InventoryTransact inventoryTransact = this.toStockRequest(transferBill);
            inventoryTransactService.run(inventoryTransact);
        }
        //Step3.批次保存转移单
        this.saveOrUpdateBatch(transferBills);
//        if(true) {throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "xx");}
        return transferBills;
    }

    /**
     * 校验转移单的各类数据是否合法
     *
     * @param transferBill 转移单
     */
    private void validateAndPrepareTransferData(TransferBill transferBill) {
        //仓库
        WareInfo wareInfo = wareInfoService.getOneByField("ware_id", transferBill.getWareId());
        Preconditions.checkNotNull(wareInfo, "根据仓库id[%s]获取仓库失败!", new Object[]{transferBill.getWareId()});
        transferBill.setWareCode(wareInfo.getWareCode());
        transferBill.setWareName(wareInfo.getWareName());
        //来源库位 所有类型都需要校验
        CellInfo fromCellInfo = cellInfoService.findByCodeAndWareId(transferBill.getFromCellCode(), transferBill.getWareId());
        Preconditions.checkNotNull(fromCellInfo, "根据仓库id[%s],库位[%s]获取来源库位失败!", new Object[]{transferBill.getWareId(), transferBill.getFromCellCode()});
        //目标库位
        //上架，转移，拣货 需要校验
        CellInfo toCellInfo = cellInfoService.findByCodeAndWareId(transferBill.getToCellCode(), transferBill.getWareId());
        Preconditions.checkNotNull(toCellInfo, "根据仓库id[%s],库位[%s]获取目标库位失败!", new Object[]{transferBill.getWareId(), transferBill.getToCellCode()});
        //物料
        ItemInfo itemInfo = itemInfoService.getOneByField("item_code", transferBill.getItemCode());
        Preconditions.checkNotNull(itemInfo, "根据物料编码[%s]获取物料失败!", new Object[]{transferBill.getItemCode()});
        transferBill.setItemName(itemInfo.getItemName());
    }

    private InventoryTransact toStockRequest(TransferBill transferBill) {
        InventoryTransact inventoryTransact = new InventoryTransact();
        //Step1.准备数据
        inventoryTransact.setFromInventoryId(transferBill.getFromInvId());
        //仓库
        inventoryTransact.setWareId(transferBill.getWareId());
        inventoryTransact.setWareName(transferBill.getWareName());
        //
        inventoryTransact.setFromInventoryId(transferBill.getFromInvId());
        //库位
        inventoryTransact.setFromCellCode(transferBill.getFromCellCode());
        inventoryTransact.setToCellCode(transferBill.getToCellCode());
        //容器
        inventoryTransact.setFromBoxCode(transferBill.getFromBoxCode());
        inventoryTransact.setToBoxCode(transferBill.getToBoxCode());
        //物料
        inventoryTransact.setItemCode(transferBill.getItemCode());
        inventoryTransact.setItemName(transferBill.getItemName());
        //批次
        inventoryTransact.setFromBatchId(transferBill.getBatchId());
        inventoryTransact.setFromBatchName(transferBill.getBatchName());
        inventoryTransact.setToBatchId(transferBill.getBatchId());
        inventoryTransact.setToBatchName(transferBill.getBatchName());
        //数量
        inventoryTransact.setToQuantity(transferBill.getQty().doubleValue());
        //包装 转换率
        inventoryTransact.setFromPackDetailId(transferBill.getPackDetailId());
        inventoryTransact.setToPackDetailId(transferBill.getPackDetailId());
        inventoryTransact.setToTransRatio(1.0);
        inventoryTransact.setFromTransRatio(1.0);
        //创建人 时间
        inventoryTransact.setCreateUserId(transferBill.getConfirmUserId());
        inventoryTransact.setCreateUserName(transferBill.getConfirmUserName());
        inventoryTransact.setCreateTime(DateUtil.now());
        //事务类型
        inventoryTransact.setTransactType(handleTransactType(transferBill.getBillType()));
        //来源单据号
        inventoryTransact.setBillNo(transferBill.getTransferBillCode());
        //冻结标识
        inventoryTransact.setState(transferBill.getFreezeFlag());
//        inventoryTransact.setAsnStockId(transferBill.getAsnStockId());
//        inventoryTransact.setAsnStockName(transferBill.getAsnStockName());
        //Step2.保存，返回
        inventoryTransactService.save(inventoryTransact);
        return inventoryTransact;
    }

    /**
     * 转移单类型到库存类型的转换
     *
     * @param billType 转移单类型
     * @return 库存事物类型
     */
    private Integer handleTransactType(Integer billType) {
        Integer transactType;
        switch (billType) {
            case 0: //InStockConstant.TRANS_TYPE_PACK_BOX
                transactType = InventoryConstant.TRANSACT_TYPE_PACK;
                break;
            case 2: //InStockConstant.TRANS_TYPE_UPPER
                transactType = InventoryConstant.TRANSACT_TYPE_UP;
                break;
            case 4: //InStockConstant.TRANS_TYPE_MOVE
                transactType = InventoryConstant.TRANSACT_TYPE_MOVE;
                break;
            case 6: //InStockConstant.TRANS_TYPE_PICK
                transactType = InventoryConstant.TRANSACT_TYPE_PICK;
                break;
//            case 8: //InStockConstant.TRANS_TYPE_PICK2
//                transactType = InventoryConstant.TRANSACT_TYPE_PACK;-
//                break;
            default:
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未匹配到转移单类型");
        }
        return transactType;
    }

    @Override
    public List<TransferBill> selectBillList(TransferBillCriteria transferBillCriteria) {
        // 返回查询的数据
        return transferBillMapper.selectBillList(transferBillCriteria);
    }



    /**
     * 直发虚仓出库
     *
     * @param detailId
     */
    @Override
    public void virtual(List<String> detailId,CurrentUser currentUser) {

        Set<OutDetail> outSet = new HashSet<>();
        Set<SoDetail> set = new HashSet<>();
        List<WaveDetail> waveDetails = waveDetailService.listByIds(detailId);
        if (waveDetails.stream().filter(item -> item.getState() == 4).count() > 0) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该订单已入库");
        }

        //待出库的所有物料
        List<SoDetail> soDetailList = soDetailService.list(new QueryWrapper<SoDetail>().in("wave_detail_id", detailId));
        //根据波次详情分组
        Map<Integer, List<SoDetail>> detailMap = soDetailList.stream().collect(Collectors.groupingBy(SoDetail::getWaveDetailId));
        //物料编码
        Set<String> itemCodeSet = waveDetails.stream().map(WaveDetail::getItemCode).collect(Collectors.toSet());
        List<Inventory> inventoryList = inventoryService.list(new QueryWrapper<Inventory>()
                .in("item_code", itemCodeSet)
                //直发虚仓仓库id待定
                .in("asn_stock_id", 11)
                .ne("cell_code", 285000)
                .ne("cell_code", 285333)
        );
        //物料编码分组
        Map<String, List<Inventory>> inventoryMap = inventoryList.stream().collect(Collectors.groupingBy(Inventory::getItemCode));

        List<Inventory> inventorieUpdate = new ArrayList<>();
        for (WaveDetail waveDetail : waveDetails) {
            List<SoDetail> soDetails = detailMap.get(waveDetail.getWaveDetailId());
            double allottedQuantity = 0.00;
            //循环遍历任务详情
            for (SoDetail soDetail : soDetails) {
                OutDetail outDetail = new OutDetail();
                //带填补数量
                double soQty = soDetail.getOrderQuantity() - soDetail.getDeliveryQuantity();
                if (soQty == 0) {
                    continue;
                }
                List<Inventory> inventories = inventoryMap.get(waveDetail.getItemCode());
                for (Inventory inv : inventories) {
                    double invQty = inv.getQuantity() - inv.getAllotQuantity() - inv.getFreezeQuantity();
                    if (invQty <= soQty) {
                        soDetail.setDeliveryQuantity(soDetail.getDeliveryQuantity() + invQty);
                        soDetail.setState(WareTaskConstant.SO_DETAIL_STATE_PART_SEND);
                        set.add(soDetail);
                        BeanUtils.copyProperties(soDetail, outDetail);
                        outDetail.setBoxCode(inv.getBoxCode());
                        outDetail.setCellCode(inv.getCellCode());
                        outDetail.setBatchName(inv.getBatchName());
                        outDetail.setErpAreaId(inv.getErpAreaId());
                        outSet.add(outDetail);
                        allottedQuantity += invQty;
                        inv.setAllotQuantity(inv.getAllotQuantity()+invQty);
                        inventorieUpdate.add(inv);
                    } else {
                        if (soQty==0) {
                            break;
                        }
                        //库存足够分配，全部填满SO的数量
                        soDetail.setDeliveryQuantity(soQty);
                        soDetail.setState(WareTaskConstant.SO_DETAIL_STATE_ALL_SEND);
                        BeanUtils.copyProperties(soDetail,outDetail);
                        outDetail.setBoxCode(inv.getBoxCode());
                        outDetail.setCellCode(inv.getCellCode());
                        outDetail.setBatchName(inv.getBatchName());
                        outDetail.setErpAreaId(inv.getErpAreaId());
                        outSet.add(outDetail);
                        set.add(soDetail);
                        //扣减已分配的库存数量
                        inv.setAllotQuantity(inv.getAllotQuantity()+soQty);
                        allottedQuantity += soDetail.getOrderQuantity();
                        inventorieUpdate.add(inv);
                    }
                    //修改库存数量
                }
            }
            //分配数量
            waveDetail.setAllottedQuantity(allottedQuantity);
        }
        waveDetails.forEach(menu -> {
            if (menu.getAllottedQuantity() >= menu.getQuantity()) {
                menu.setState(4);
            }
        });
        asyncService.asyncPushErp(inventorieUpdate, outSet, currentUser);
//        inventoryService.updateBatchById(inventorieUpdate);
        WaveMaster waveMaster = waveMasterService.getById(waveDetails.get(0).getWaveMasterId());
        waveMaster.setState(WareTaskConstant.WAVE_STATE_PICKING);
        waveMasterService.updateById(waveMaster);

    }

    /**
     * 调拨单
     */

//    public void allot(List<Inventory> inventoryList,String cellCode) {
//        //生成调拨
//        double sum = inventoryList.stream().mapToDouble(item -> item.getQuantity() - item.getAllotQuantity()).sum();
//        Inventory oldInventory = inventoryList.iterator().next();
//        Inventory inventory = new Inventory();
//        BeanUtils.copyProperties(oldInventory, inventory);
//        Integer erpAreaId = cellInfoService.findbyCellCode(cellCode);
//        oldInventory.setAllotQuantity(0.00);
//        inventory.setInventoryId(null);
//        inventory.setBoxCode(codeRuleService.generateCodeByRedis("CT"));
//        inventory.setErpAreaId(erpAreaId);
//        inventory.setQuantity(sum);
//        inventory.setCellCode(cellCode);
//        inventoryService.save(inventory);
//    }

    /**
     * 转移
     *
     * @param newData
     * @param id
     */
    @Override
    public void updateErpLog(List<ErpPushLogInfo> newData, Integer id) {
        //step1.初始化数据
        ErpPushLog erpPushLog = erpPushLogService.getById(id);
        //如果为调拨单

        List<ErpPushLogInfo> oldData = erpPushLogInfoService.list(new QueryWrapper<ErpPushLogInfo>().eq("erp_push_id", id));
        Map<Integer, List<ErpPushLogInfo>> infoMap = oldData.stream().collect(Collectors.groupingBy(ErpPushLogInfo::getId));
        List<Inventory> inventoryList = inventoryService.list(new QueryWrapper<Inventory>().in("box_code", oldData.stream().map(ErpPushLogInfo::getBoxCode).collect(Collectors.toSet())));
        //根据容器号分组
        Map<String, List<Inventory>> inventoryMap = inventoryList.stream().collect(Collectors.groupingBy(Inventory::getBoxCode));
        List<TransferBill> transferBills = new ArrayList<>();

        //要增加的物料
        List<ErpPushLogInfo> add = new ArrayList<>();
        //减少的物料  生成转移单
        List<ErpPushLogInfo> minus = new ArrayList<>();
        for (ErpPushLogInfo newDatum : newData) {
            ErpPushLogInfo erpPushLogInfo = new ErpPushLogInfo();
            if (ObjectUtil.isNotEmpty(infoMap.get(newDatum.getId()))) {
                ErpPushLogInfo next = infoMap.get(newDatum.getId()).iterator().next();
                BeanUtils.copyProperties(newDatum, erpPushLogInfo);
                //如果要修改的数量比原始数量
                if (newDatum.getQty() > next.getQty()) {
                    throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, newDatum.getItemName()+"不能大于原始数量！");
                }
                if (newDatum.getQty() <= next.getQty()) {
                    erpPushLogInfo.setQty(next.getQty() - newDatum.getQty());
                    minus.add(erpPushLogInfo);
                }
            }
        }



        List<ErpPushLogInfo> infos = newData.stream().filter(item->ObjectUtil.isNotEmpty(item.getClose())&&!item.getClose()).collect(Collectors.toList());
        List<ErpPushLogInfo> pushLogInfos = newData.stream().filter(item->ObjectUtil.isNotEmpty(item.getClose())&&item.getClose()).collect(Collectors.toList());
        this.merge(minus, inventoryMap, inventoryList, transferBills, true);
        this.merge(infos, inventoryMap, inventoryList, transferBills, false);
        this.saveBatch(transferBills); //生成转移单
        inventoryService.updateBatchById(inventoryList); //处理库存
        ;
        Map<String, String> map = pushErpService.twiceSend(this.getBean(erpPushLog, pushLogInfos));
        String code = map.get("code");
        String msg = map.get("msg");
        if (!"200".equals(code)) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, map.get("msg"));
        }
        erpPushLog.setCode(code);
        erpPushLog.setMsg(msg);
        erpPushLogService.updateById(erpPushLog);
    }

    /**
     * @param criteria
     * @return
     */
    @Override
    public List<AsnMaster> alignList(DispatCriteria criteria) {
      return   baseMapper.alignList(criteria);
    }

    /**
     * 详情
     *
     * @param billNo
     * @return
     */
    @Override
    public SoDetailVo detail(String billNo) {
        SoDetailVo soDetailVo = new SoDetailVo();
        List<SoDetail> soDetailList =   soDetailService.findByOrderNo(billNo);
        if (ObjectUtil.isNotEmpty(soDetailList)) {
//            soDetailVo.setAll(soDetailList); // 全部项
            soDetailVo.setLend(soDetailService.lendDetail(soDetailList));//借料项
        }
        return soDetailVo;
    }

    /**
     * 查其他生产任务单中的数据
     *
     * @param itemCode
     * @param billNo
     * @return
     */
    @Override
    public List<SoDetail> beBeing(String itemCode, String billNo) {
       return soDetailService.beBeing(itemCode, billNo);
    }

    /**
     * 齐套提交
     *
     * @param soDetailVo
     */


    /**
     * 聚源回传ERP
     *
     * @param upperData
     */
    @Override
    public void createUpper(UpperData upperData) {
        //Step1. 获取库存转换为Map
        List<AsnDetail> asnDetailList = new ArrayList<>();
        List<Integer> invIds = upperData.getUpperList().stream().map(item -> item.getFromInvId()).collect(Collectors.toList());
        List<Inventory> invList = inventoryService.listByIds(invIds);
        List<String> accreptBillNos = invList.stream().map(Inventory::getBillNo).collect(Collectors.toList());
        List<AcceptRecord> acceptRecords = acceptRecordService.list(new QueryWrapper<AcceptRecord>().in("accept_record_code", accreptBillNos));
        List<String> detailNos = acceptRecords.stream().map(item -> item.getAsnDetailNo()).collect(Collectors.toList());
        List<AsnDetail> asnDetails = asnDetailMapper.selectList(new QueryWrapper<AsnDetail>().in("detail_no", detailNos));
        //收货单
        Map<String, AcceptRecord> acceptMap = convertMap(acceptRecords, AcceptRecord::getAcceptRecordCode);
        //库存
        Map<Integer, Inventory> invMap = convertMap(invList, Inventory::getInventoryId);
        //入库任务明细
        Map<String, AsnDetail> detailMap = convertMap(asnDetails, AsnDetail::getDetailNo);

        for (Upper upper : upperData.getUpperList()) {
            //库存，收货单，入库任务明细
            Inventory inventory = invMap.get(upper.getFromInvId());
            AcceptRecord acceptRecord = acceptMap.get(inventory.getBillNo());
            AsnDetail asnDetail = detailMap.get(acceptRecord.getAsnDetailNo());
            asnDetail.setStockId(cellInfoService.findbyCellCode(upper.getCellCode()));
            asnDetail.setQty(upper.getQuantity());
            asnDetail.setBatchName(inventory.getBatchName());
            asnDetailList.add(asnDetail);
        }
        AsnDetail asnDetail = asnDetailList.listIterator().next();
        AsnMaster asnMaster = asnMasterService.getOne(new QueryWrapper<AsnMaster>().eq("bill_no", asnDetail.getBillNo()));
        //回传ERP
        strategyEnterService.resolveAsn(asnMaster, asnDetailList);


    }


    public OrderToErpBO getBean(ErpPushLog erpPushLog,List<ErpPushLogInfo> detail) {
        OrderToErpBO orderToErpBO = new OrderToErpBO();
        BeanUtils.copyProperties(erpPushLog, orderToErpBO);
        orderToErpBO.setBillDate(DateUtils.getNowDateString());
        List<OrderDetailBO> orderDetailBOList = new ArrayList<>();
        detail.forEach(item->{
            OrderDetailBO orderDetailBO = new OrderDetailBO();
            BeanUtils.copyProperties(item, orderDetailBO);
            orderDetailBOList.add(orderDetailBO);
        });
        orderToErpBO.setDetails(orderDetailBOList);
        return orderToErpBO;

    }

    public void merge(List<ErpPushLogInfo> list,Map<String, List<Inventory>> inventoryMap,List<Inventory> inventoryList,List<TransferBill> transferBills,Boolean flg) {
        for (ErpPushLogInfo erpPushLogInfo : list) {
            TransferBill transferBill = new TransferBill();
            //查找库存
            Inventory inventory = inventoryMap.get(erpPushLogInfo.getBoxCode()).iterator().next();
            //修改库存
            if (flg) {
                inventory.setQuantity(inventory.getQuantity()-erpPushLogInfo.getQty());
            }
            //生成转移任务
            BeanUtils.copyProperties(inventory, transferBill);
            String code = codeRuleService.generateCode(SystemManageConstant.CODE_RULE_TRANS);
            transferBill.setTransferBillCode(code);
            transferBill.setBillType(4);
            transferBill.setState(0);
            transferBill.setFromCellCode(inventory.getCellCode());
            transferBill.setFromBoxCode(inventory.getBoxCode());
            transferBill.setQty(BigDecimal.valueOf(inventory.getQuantity()));
            transferBills.add(transferBill);
            inventoryList.add(inventory);
        }
    }

}